package com.jack.thinking.java._22.swing.concurrent;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.swing.*;

import com.utils.SwingConsole;

public class InterruptableLongRunningTask extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private JButton b1 = new JButton("Start Long Running Task");
	private JButton b2 = new JButton("End Long Running Task");

	ExecutorService executor = Executors.newSingleThreadExecutor();
	
	public InterruptableLongRunningTask() {
		b1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				Task task = new Task();
				executor.execute(task);
				System.out.println(task + " add to the queque");
			}
		});
		
		b2.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				executor.shutdownNow();
			}
		});
		
		setLayout(new FlowLayout());
		add(b1);
		add(b2);
	}
	
	public static void main(String[] args) {
		SwingConsole.run(new InterruptableLongRunningTask(), 200, 150);
	}
}

class Task implements Runnable{
	private static int counter = 0;
	private final int id = counter++;

	@Override
	public void run() {
		System.out.println(this + " started");
		
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			System.out.println(this + " interrupted");
			return;
		}
		
	}
	
	public String toString() {
		return "Task " + id;
	}
	
	public long id() {
		return id;
	}
	
}